package org.mca.mcaweb.dao;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.interceptor.InvocationContext;
import javax.persistence.EntityManager;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.mca.mcaweb.bean.LoggedUser;
import org.mca.mcaweb.entity.Log;
import org.mca.mcaweb.entity.Usua;

public class LogDAO implements Serializable {
	
	private static final long serialVersionUID = -2110669840113284277L;

	@Inject
	private LoggedUser loggedUser;
	
	@Inject
	private EntityManager em;
	
	private Log log;
	
	public void registerLog(InvocationContext ctx){

		if(this.loggedUser.getUsua() != null){
			this.log = new Log();
//			this.log.setRegisterDate(Calendar.getInstance());
			this.log.setBean(ctx.getMethod().getDeclaringClass().getName());
			this.log.setMethod(ctx.getMethod().getName());
			this.log.setUsua(loggedUser.getUsua());
			this.save(log);
		}
		if(ctx.getMethod().getDeclaringClass().getSimpleName().equals("RecoverPasswordBean")) {
			loggedUser.setUsua(null);
		}
	}
	
	private void save(Log log) {
		if(!em.getTransaction().isActive()){
			em.getTransaction().begin();
			em.persist(log);
			em.getTransaction().commit();
		}else{
			em.persist(log);
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Log> logsByFilters(Date startDate, Date endDate, Usua usua) {
		
		Session session = (Session) em.getDelegate();
		
		Criteria criteria = session.createCriteria(Log.class);
		
		if(startDate != null){
			criteria.add(Restrictions.ge("date", startDate));
		}		
		
		if(endDate != null){
			criteria.add(Restrictions.le("date", endDate));
		}
		
		if(usua != null){
			criteria.createAlias("user", "u");
			criteria.add(Restrictions.eq("u.usuacodigo", usua.getUsuacodigo()));
		}
		
		return (List<Log>) criteria.list();
	}

}
